package cn.sam.servlet;


import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

//继承Tomcat中的HttpServlet
@WebServlet("/Http")
public class HelloHttpServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("这里是HelloServlet");
        System.out.println(req.getSession().getServletContext().getAttribute("c"));

        //获取session对象
        HttpSession session = req.getSession();
        //在session域中设置值
        session.setAttribute("值的名字","对应的值");
        //如何从session中取出数据
        Object s = session.getAttribute("值的名字");
        System.out.println(s); //输出是 : 对应的值

        //获取servletContext对象(通过session对象获取)
        ServletContext servletContext = session.getServletContext();
        //在ServletContext域中设置值
        servletContext.setAttribute("值的名字","对应的值");
        //如何从ServletContext中取出数据
        Object c = servletContext.getAttribute("值的名字");
        System.out.println(c); //输出是 : 对应的值

        //如何使用Cookie
        //创建Cookie对象
        Cookie cookie = new Cookie("名字","Cookie的值");
        //通过响应对象把Cookie响应给浏览器
        resp.addCookie(cookie);
        //如何获取浏览器中的Cookie(全部,是数组类型)
        Cookie[] cookies = req.getCookies();
        for (Cookie cookie1 : cookies) {
            System.out.println(cookie1);
        }
    }
}
